package com.soujiayi.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;


import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.view.View.OnTouchListener;
import android.view.Window;
import android.view.WindowManager.LayoutParams;
import android.view.inputmethod.InputMethodManager;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.LinearLayout;
import android.widget.Toast;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.ExpandableListView.OnGroupClickListener;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.soujiayi.adapter.ProductListAdapter;
import com.soujiayi.adapter.ProductSelectAdapter;
import com.soujiayi.adapter.ProductSortListAdapter;
import com.soujiayi.model.Product;
import com.soujiayi.model.ProductSelectItem;
import com.soujiayi.model.Products;
import com.soujiayi.net.HttpRequester;
import com.soujiayi.net.NetworkUtils;
import com.soujiayi.util.CommonUtils;
import com.soujiayi.util.Constants;
import com.soujiayi.view.NetworkUnavailableDialog;
import com.soujiayi.view.NormalDialog;

public class ProductMainActivity extends Activity {

	private View productMainView;
	private LayoutInflater layoutInflater;
	private String searchKey = "";
	private String cid = "";
	private ViewPager mTabPager;
	private ArrayList<View> views = new ArrayList<View>();
	private String sid = "";
	
	// product list view
	private ListView productListView;
	private ProductListAdapter productListAdapter;
	private ArrayList<Product> listitem = new ArrayList<Product>();
	private TextView productCountView;
	private TextView currentProductView;
	private String countText = "";
	private String currentPositionText = "";
	private Button backBtn;
	private Button selectBtn;
	private int count = 0;
	private int currentCount = 0;
	
	private RelativeLayout rl_product_count;
	private LinearLayout ll_product_loading;
	private View productListFooter;
	private LinearLayout ll_product_loadmore;
	private TextView tv_product_loadmore_end;
	private TextView tv_product_loadmore_reload;
	private LinearLayout ll_is_loading;
	
	private View productSelectView;
	private ExpandableListView productSelectListView;
	private ProductSelectAdapter productSelectAdapter;
	private ArrayList<ArrayList<ProductSelectItem>> productSelectData = new ArrayList<ArrayList<ProductSelectItem>>();
	private List<Integer> productSelectGroup = new ArrayList<Integer>();
	private RelativeLayout priceScopeLayout;
	private Button selectDoneBtn;
	private Button backToPLBtn;
	private EditText fromPriceView;
	private EditText toPriceView;
	//private TextView inValidPriceMessage;
	private List<String> select_catids = new ArrayList<String>();
	private List<String> select_attrids = new ArrayList<String>();
	private List<String> select_mallids = new ArrayList<String>();
	private List<String> select_brandids = new ArrayList<String>();
	private String ob = "0";
	private String ou = "0";
	private String pst = "0";
	
	private SortDialog sortDialog;
	private ListView sortListView;
	private ProductSortListAdapter sortListAdapter;
	
	private boolean isCategorySearch = false;
	
	//private TextView reloadText;
	
	private Handler productSearchHandler;
	private HttpRequester httpRequester;
	//private Handler goodsDetailHandler;
	
	private boolean isFirstSearch = true;
	private boolean clearRecords = false;
	
	private boolean isSearching = false;
	private boolean isNeedReload = false;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		((MyApplication) this.getApplication()).addActivity(this);
		setContentView(R.layout.product_main);

		Intent intent = this.getIntent();
		if(intent.getExtras().get(Constants.SEARCH_INTENT_KEY) != null){
			searchKey = intent.getExtras().get(Constants.SEARCH_INTENT_KEY).toString();
		}
		if(intent.getExtras().get(Constants.PRODUCT_CID) != null){
			cid = intent.getExtras().get(Constants.PRODUCT_CID).toString();
		}
		sid = ((MyApplication)this.getApplication()).getSessionId();
		isCategorySearch = intent.getBooleanExtra(Constants.PRODUCT_IS_CLASSIFY_SHOWED, false);
		
        layoutInflater = LayoutInflater.from(this);
		initProductMainView();
		initProductSelectView();
		initViewPager();
		
		goodsSearchHandler();
		//goodsDetailHandler();
		
		// network state receiver
		IntentFilter filter = new IntentFilter();
		filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
		registerReceiver(mNetworkStateReceiver, filter);
		
		// load data
		searchGoods(true);
		
	}
	
	// 显示搜索结果
	private void goodsSearchHandler(){
		productSearchHandler = new Handler(){
		    @Override
		    public void handleMessage(Message msg) {
		        super.handleMessage(msg);
		        Bundle data = msg.getData();
		        
		        boolean isError = data.getBoolean(Constants.IS_ERROR);
		        if(isError){
	    			ll_product_loading.setVisibility(View.GONE);
	    			productListView.setVisibility(View.VISIBLE);
	    			ll_product_loadmore.setVisibility(View.VISIBLE);
	    			
					tv_product_loadmore_end.setVisibility(View.GONE);
					ll_is_loading.setVisibility(View.GONE);
					tv_product_loadmore_reload.setVisibility(View.VISIBLE);
					isNeedReload = true;
					if(clearRecords){
						rl_product_count.setVisibility(View.GONE);
						listitem.removeAll(listitem);
						productListAdapter.notifyDataSetChanged();
					}
					isSearching = false;
		        	return;
		        }
		        
		        
		        Products products = (Products) data.getSerializable(Constants.PRODUCTS);
		        count = products.getTotal_found();
	        	productCountView.setText(countText.replace("?", String.valueOf(count)));
		        if(isFirstSearch){
		        		isFirstSearch = false;
		        		currentProductView.setText(currentPositionText.replace("?", "0"));
		        		productSelectData.removeAll(productSelectData);
		        		productSelectGroup.removeAll(productSelectGroup);
		        		if(products.getCatlist() != null && products.getCatlist().size() > 0 && !isCategorySearch){
		        			productSelectData.add(products.getCatlist());
		        			productSelectGroup.add(Constants.PRODUCT_SELECT_TYPE);
		        		}
		        		if(products.getAttrlist() != null && products.getAttrlist().size() > 0){
		        			productSelectData.add(products.getAttrlist());
		        			productSelectGroup.add(Constants.PRODUCT_SELECT_ATTRIBUTE);
		        		}
		        		if(products.getMalllist() != null && products.getMalllist().size() > 0){
		        			productSelectData.add(products.getMalllist());
		        			productSelectGroup.add(Constants.PRODUCT_SELECT_SELLER);
		        		}
		        		if(products.getBrandlist() != null && products.getBrandlist().size() > 0){
		        			productSelectData.add(products.getBrandlist());
		        			productSelectGroup.add(Constants.PRODUCT_SELECT_BRAND);
		        		}
		        		productSelectGroup.add(Constants.PRODUCT_SELECT_PRICE_SCOPE);
		        		productSelectData.add(new ArrayList<ProductSelectItem>());
		    			
		        		productSelectAdapter.notifyDataSetChanged();
		        }else{
		        	if(clearRecords){
		        		listitem.removeAll(listitem);
		        		currentCount = 0;
		        		productListView.requestFocusFromTouch();
		          		productListView.setSelection(0);
		        	}
		        }
		        
		        if(products.getProductlist() != null){
		        	currentCount += products.getProductlist().size();  
			        listitem.addAll(products.getProductlist());
		        }
		        productListAdapter.notifyDataSetChanged();
	        	
		        if(count > 0){
					if(currentCount >= count){
						tv_product_loadmore_end.setVisibility(View.VISIBLE);
						ll_is_loading.setVisibility(View.GONE);
					}else{
						tv_product_loadmore_end.setVisibility(View.GONE);
						if(count <= Constants.PRODUCT_SEARCH_LIMIT){
							ll_is_loading.setVisibility(View.GONE);
						}else{
							if(currentCount >= 6){
								ll_is_loading.setVisibility(View.VISIBLE);
							}else{
								ll_is_loading.setVisibility(View.GONE);
							}
						}
					}

		        }else{
		        	ll_product_loadmore.setVisibility(View.VISIBLE);
		        	tv_product_loadmore_end.setVisibility(View.GONE);
		        	ll_is_loading.setVisibility(View.GONE);
		        }
		  		rl_product_count.setVisibility(View.VISIBLE);
    			productListView.setVisibility(View.VISIBLE);
    			ll_product_loading.setVisibility(View.GONE);
    			
    			isSearching = false;
		    }
		};	
		httpRequester = new HttpRequester(this,1, productSearchHandler);
	}
	
//	public void goodsDetailHandler(){
//		goodsDetailHandler = new Handler(){
//		    @Override
//		    public void handleMessage(Message msg) {
//		        super.handleMessage(msg);
//		        
//		        httpRequester.setHandler(productSearchHandler);
//		        
//		        Bundle data = msg.getData();
//		        Product product = (Product) data.getSerializable(Constants.PRODUCT);
//				
//				Intent intent;
//				if(product.getCompare() != null && product.getCompare().getMallnum() > 1){
//					intent = new Intent(ProductMainActivity.this, ProductParityActivity.class);
//					intent.putExtra(Constants.PRODUCT_IS_PARITY, true);
//				}else{
//					intent = new Intent(ProductMainActivity.this, ProductDetailActivity.class);
//					intent.putExtra(Constants.PRODUCT_IS_PARITY, false);
//				}
//				intent.putExtra(Constants.PRODUCT, product);
//				
//				startActivity(intent);
//				overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
//				isSearching = false;
//		    }
//        };
//	}
	
	private void initViewPager(){
		mTabPager = (ViewPager) findViewById(R.id.product_main_tabpager);
		
        //每个页面的view数据
        views = new ArrayList<View>();
        views.add(productMainView);
        views.add(productSelectView);
        PagerAdapter pagerAdapter = new ProductMainPagerAdapter();
        mTabPager.setAdapter(pagerAdapter);
	}

	private void initProductMainView(){
        productMainView = layoutInflater.inflate(R.layout.product_list, null);
		productListView = (ListView) productMainView.findViewById(R.id.product_list_productListView);
		productListFooter = layoutInflater.inflate(R.layout.load_more, null);		
		
		ll_product_loadmore = (LinearLayout) productListFooter.findViewById(R.id.ll_loadmore);
		tv_product_loadmore_end = (TextView) productListFooter.findViewById(R.id.tv_loadmore_end);
		tv_product_loadmore_reload = (TextView) productListFooter.findViewById(R.id.tv_loadmore_reload);
		ll_is_loading = (LinearLayout) productListFooter.findViewById(R.id.ll_is_loading);
		productListView.addFooterView(productListFooter);
		
		backBtn = (Button) productMainView.findViewById(R.id.product_list_backBtn);
		if(isCategorySearch){
			backBtn.setBackgroundResource(R.drawable.arrow_left);
		}else{
			backBtn.setBackgroundResource(R.drawable.home_icon);
		}
		
		selectBtn = (Button) productMainView.findViewById(R.id.product_list_selectBtn);
		selectBtn.setOnClickListener(new ViewSwitchOnClickListener(1));

		productListAdapter = new ProductListAdapter(this, listitem);
		productListView.setAdapter(productListAdapter);

		ll_product_loading = (LinearLayout) productMainView.findViewById(R.id.ll_product_loading);
		rl_product_count = (RelativeLayout) productMainView.findViewById(R.id.rl_product_count);
		
		countText = this.getResources().getString(R.string.product_list_headerText1);
		productCountView = (TextView) productMainView.findViewById(R.id.product_list_productCount);
		productCountView.setText(countText.replace("?", String.valueOf(count)));
		
		currentPositionText = this.getResources().getString(R.string.product_list_headerText2);
		currentProductView = (TextView) productMainView.findViewById(R.id.product_list_currentProduct);
		currentProductView.setText(currentPositionText.replace("?", "0"));

		productListView.setOnScrollListener(new ProductListOnScrollListener());
		
		productListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int position,
					long arg3) {
				if(!NetworkUtils.isNetworkConnected(ProductMainActivity.this)){
					Toast.makeText(
							ProductMainActivity.this,
							ProductMainActivity.this
									.getString(R.string.network_unavailable_message),
							Toast.LENGTH_LONG).show();
					return;
				}
				Intent intent;
				Product product = listitem.get(position);
				if(product.getCompare() != null && product.getCompare().getMallnum() > 1){
					intent = new Intent(ProductMainActivity.this, ProductParityActivity.class);
					intent.putExtra(Constants.PRODUCT_IS_PARITY, true);
//					ProductAttributes attributes = new ProductAttributes();
//					attributes.setAttrlist(tempproducts.getAttrlist());
//					intent.putExtra(Constants.PRODUCT_ATTRIBUTE, attributes);
				}else{
					intent = new Intent(ProductMainActivity.this, ProductDetailActivity.class);
					intent.putExtra(Constants.PRODUCT_IS_PARITY, false);
				}
				intent.putExtra(Constants.PRODUCT, product);
				
				startActivity(intent);
				overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
//				if(!isSearching){
//					isSearching = true;
//					Product product = listitem.get(position);
//					httpRequester.setHandler(goodsDetailHandler);
//					HashMap<String, String> parameters = new HashMap<String, String>();
//					parameters.put("goodsid", product.getGoodsid());
//					parameters.put("sid", sid);
//					httpRequester.getGoodsDetail(parameters);
//				}
			}
		});
		
	}
	
	private void initProductSelectView(){
        productSelectView = layoutInflater.inflate(R.layout.product_select, null);
        productSelectListView = (ExpandableListView) productSelectView.findViewById(R.id.product_select_productSelectListView);
        priceScopeLayout = (RelativeLayout) productSelectView.findViewById(R.id.product_select_priceScopeLayout);
		selectDoneBtn = (Button) productSelectView.findViewById(R.id.product_select_selectDoneBtn);
		selectDoneBtn.setOnClickListener(new ViewSwitchOnClickListener(0));
		backToPLBtn = (Button) productSelectView.findViewById(R.id.product_select_backToPLBtn);
		backToPLBtn.setOnClickListener(new ViewSwitchOnClickListener(0));
		fromPriceView = (EditText) productSelectView.findViewById(R.id.product_select_fromPrice);
		toPriceView = (EditText) productSelectView.findViewById(R.id.product_select_toPrice);
//		inValidPriceMessage = (TextView) productSelectView.findViewById(R.id.product_select_priceInvalidMessage);
		
		fromPriceView.setOnFocusChangeListener(new priceOnFocusChangeListener());
		toPriceView.setOnFocusChangeListener(new priceOnFocusChangeListener());
		
//		fromPriceView.addTextChangedListener(new PriceTextWatcher());
//		toPriceView.addTextChangedListener(new PriceTextWatcher());
		
		productSelectView.setOnTouchListener(new OnTouchListener() {
            public boolean onTouch(View v, MotionEvent event) {
            	productSelectView.setFocusable(true);
            	productSelectView.setFocusableInTouchMode(true);
            	productSelectView.requestFocus();
                return false;
            }
		});
        
        productSelectData = new ArrayList<ArrayList<ProductSelectItem>>();
        
        productSelectAdapter = new ProductSelectAdapter(this, productSelectGroup, productSelectData);  
        productSelectListView.setAdapter(productSelectAdapter);
        
        productSelectListView.setOnChildClickListener(new OnChildClickListener() {
			@Override
			public boolean onChildClick(ExpandableListView parent, View v,
					int groupPosition, int childPosition, long id) {
				int index = (Integer) productSelectAdapter.getGroup(groupPosition);
				if(index != Constants.PRODUCT_SELECT_PRICE_SCOPE){
					boolean isSelected = productSelectData.get(groupPosition).get(childPosition).isSelected();
					ProductSelectItem item = productSelectData.get(groupPosition).get(childPosition);
					String itemid = item.getId();

					if(index == Constants.PRODUCT_SELECT_TYPE){
						if(!isSelected){
							select_catids.add(itemid);
						}else{
							select_catids.remove(itemid);
						}
					}
					if(index == Constants.PRODUCT_SELECT_ATTRIBUTE){
						if(!isSelected){
							select_attrids.add(itemid);
						}else{
							select_attrids.remove(itemid);
						}
					}
					if(index == Constants.PRODUCT_SELECT_SELLER){
						if(!isSelected){
							select_mallids.add(itemid);
						}else{
							select_mallids.remove(itemid);
						}
					}
					if(index == Constants.PRODUCT_SELECT_BRAND){
						if(!isSelected){
							select_brandids.add(itemid);
						}else{
							select_brandids.remove(itemid);
						}
					}
					item.setSelected(!isSelected);
					productSelectAdapter.notifyDataSetChanged();
				}
				return true;
			}
		});
        
        productSelectListView.setOnGroupClickListener(new OnGroupClickListener(){
			@Override
			public boolean onGroupClick(ExpandableListView parent, View v,
					int groupPosition, long id) {
				if(groupPosition == Constants.PRODUCT_SELECT_PRICE_SCOPE){
					priceScopeLayout.setVisibility(productSelectAdapter.isPriceScopeExpand?8:0);
				}
				return false;
			}});
        
        productSelectListView.setOnTouchListener(new OnTouchListener() {	
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
				imm.hideSoftInputFromWindow(fromPriceView.getWindowToken(), 0);
				imm.hideSoftInputFromWindow(toPriceView.getWindowToken(), 0);
				return false;
			}
		});
        
	}
	
	private class ProductListOnScrollListener implements OnScrollListener{
		@Override
		public void onScroll(AbsListView view, int firstVisibleItem,
				int visibleItemCount, int totalItemCount) {
			if(listitem.size() == 0){
				currentProductView.setText(ProductMainActivity.this.getResources().getString(R.string.product_list_headerText2).replace("?", "0"));
			}else{
				currentProductView.setText(ProductMainActivity.this.getResources().getString(R.string.product_list_headerText2).replace("?", String.valueOf(firstVisibleItem + 1)));
			}
		}

		@Override
		public void onScrollStateChanged(AbsListView view, int scrollState) {
			// 当不滚动时
			if (scrollState == OnScrollListener.SCROLL_STATE_IDLE) {
				// 判断是否滚动到底部
				if (view.getLastVisiblePosition() == view.getCount() - 1) {
//					if(pst.equals(String.valueOf(currentCount))){
//						return;
//					}
					if(currentCount < count && !isNeedReload){
						pst = String.valueOf(currentCount);
						ll_is_loading.setVisibility(View.VISIBLE);
						searchGoods(false);
					}
				}
			}
		}
	}


	public class ViewSwitchOnClickListener implements View.OnClickListener {
		private int index = 0;

		public ViewSwitchOnClickListener(int i) {
			index = i;
		}
		
		@Override
		public void onClick(View v) {
			if(v.getId() == R.id.product_list_selectBtn && listitem.size() == 0){
				mTabPager.setCurrentItem(index);
				//return;
			}
			if(v.getId() == R.id.product_select_selectDoneBtn){
          		listitem.removeAll(listitem);
          		productListAdapter.notifyDataSetChanged();
				mTabPager.setCurrentItem(index);
				searchGoods(true);
			}else{
				mTabPager.setCurrentItem(index);
			}	
		}
	};
	
    private class ProductMainPagerAdapter extends PagerAdapter{
		
		@Override
		public boolean isViewFromObject(View arg0, Object arg1) {
			return arg0 == arg1;
		}
		
		@Override
		public int getCount() {
			return views.size();
		}

		@Override
		public void destroyItem(View container, int position, Object object) {
			((ViewPager)container).removeView(views.get(position));
		}
		
		@Override
		public Object instantiateItem(View container, int position) {
			((ViewPager)container).addView(views.get(position));
			return views.get(position);
		}
	};
	
	public void sort(View v) {

		if(sortDialog == null){
			sortDialog = new SortDialog(this,R.style.sortDialog);//创建Dialog并设置样式主题
			Window win = sortDialog.getWindow();
			LayoutParams params = new LayoutParams();
	
	        DisplayMetrics metric = new DisplayMetrics();
	        getWindowManager().getDefaultDisplay().getMetrics(metric);
	        
			int[] currentProductPos = new int[2];
			TextView sortBtnView = (TextView) findViewById(R.id.product_list_sortBtn);
			sortBtnView.getLocationInWindow(currentProductPos);
			
			params.gravity = Gravity.TOP;
			params.x = 0;//设置x坐标
			params.y = currentProductPos[1];//设置y坐标
			win.setAttributes(params);
			sortDialog.setCanceledOnTouchOutside(true);//设置点击Dialog外部任意区域关闭Dialog

		}
		sortDialog.show();
		
	}
	
	public class SortDialog extends AlertDialog{
		
		public SortDialog(Context context, int theme) {
		    super(context, theme);
		}

		public SortDialog(Context context) {
			super(context);
		}

		@Override
		protected void onCreate(Bundle savedInstanceState) {
		    super.onCreate(savedInstanceState);
		    setContentView(R.layout.product_sort_dialog);
		    sortListView = (ListView) this.findViewById(R.id.product_sort_sortListView);

			if(sortListAdapter == null){
				sortListAdapter = new ProductSortListAdapter(ProductMainActivity.this);
				sortListView.setAdapter(sortListAdapter);
			}
			sortListView.setOnItemClickListener(new OnItemClickListener(){
				@Override
				public void onItemClick(AdapterView<?> adapter, View view, int position, long arg3) {
					int item = (Integer) sortListAdapter.getItem(position);
					sortListAdapter.selectedItem = item;
					sortListAdapter.notifyDataSetChanged();
					sortDialog.hide();
					if(item == Constants.PRODUCT_SORT_DEFAULT){
						ob = "0";
						ou = "0";
					}else if(item == Constants.PRODUCT_SORT_PRICE_ASC){
						ob = "2";
						ou = "1";
					}else if(item == Constants.PRODUCT_SORT_PRICE_DESC){
						ob = "2";
						ou = "0";
					}
					
					searchGoods(true);
				}
			});
		}
	}
	
	
	private class priceOnFocusChangeListener implements OnFocusChangeListener{

		@Override
		public void onFocusChange(View v, boolean hasFocus) {
			InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
			if(!hasFocus){
				if(v.getId() == R.id.product_select_fromPrice){
					imm.hideSoftInputFromWindow(fromPriceView.getWindowToken(), 0); 
				}else{
					imm.hideSoftInputFromWindow(toPriceView.getWindowToken(), 0); 
				}      
			}
		}
	}
	
//	private boolean isPriceScopeSelected(){
//		boolean isSelected = true;
//		String fromPrice = fromPriceView.getText() == null ? null : fromPriceView.getText().toString();
//		String toPrice = toPriceView.getText() == null ? null : toPriceView.getText().toString();
//		if(CommonUtils.isEmpty(fromPrice) || CommonUtils.isEmpty(toPrice)){
//			isSelected = false;
//		}
//		return isSelected;
//	}
//	
//	private boolean validatePriceScope(){
//		boolean isValid = true;
//		String errorMessage = "";
//		String fromPrice = fromPriceView.getText() == null ? null : fromPriceView.getText().toString();
//		String toPrice = toPriceView.getText() == null ? null : toPriceView.getText().toString();
//		if(!CommonUtils.isEmpty(fromPrice)){
//			if(!CommonUtils.isNumeric(fromPrice)){
//				errorMessage = getResources().getString(R.string.product_select_fromprice_invalid);
//				isValid = false;
//			}
//		}
//		if(!CommonUtils.isEmpty(toPrice)){
//			if(!CommonUtils.isNumeric(toPrice)){
//				errorMessage = getResources().getString(R.string.product_select_toprice_invalid);
//				isValid = false;
//			}
//		}
//		if(!isValid){
//			NormalDialog dialog = new NormalDialog(ProductMainActivity.this,
//					R.style.normalDialog, errorMessage);
//			dialog.show();
//		}
//		
//		return isValid;
//	}
	
//	private class PriceTextWatcher implements TextWatcher{
//
//		@Override
//		public void afterTextChanged(Editable s) {
//			inValidPriceMessage.setText("");
//		}
//
//		@Override
//		public void beforeTextChanged(CharSequence s, int start, int count,
//				int after) {
//
//		}
//
//		@Override
//		public void onTextChanged(CharSequence s, int start, int before,
//				int count) {
//
//		}
//	}
	
	public void searchGoods(boolean clearRecords){
		this.clearRecords = clearRecords;
		if(!NetworkUtils.isNetworkConnected(this)){
			tv_product_loadmore_end.setVisibility(View.GONE);
			ll_is_loading.setVisibility(View.GONE);
			tv_product_loadmore_reload.setVisibility(View.VISIBLE);
			isNeedReload = true;
			if(this.clearRecords){
				rl_product_count.setVisibility(View.GONE);
				listitem.removeAll(listitem);
				productListAdapter.notifyDataSetChanged();
			}
			return;
		}
		if(isSearching){
			return;
		}
		isSearching = true;

		HashMap<String, String> parameters = new HashMap<String, String>();
		if(isCategorySearch){
			parameters.put("cid", this.cid);
		}else{
			parameters.put("q", this.searchKey);
		}
		parameters.put("sid", sid);
		if(isFirstSearch){
			parameters.put("hasstat", "1");
		}
		
		if(this.clearRecords){
			rl_product_count.setVisibility(View.INVISIBLE);
			productListView.setVisibility(View.INVISIBLE);
			ll_product_loading.setVisibility(View.VISIBLE);
		}
		parameters.put("ob", ob);
		parameters.put("ou", ou);
		
		parameters.put("pst", pst);
		parameters.put("limit", Integer.toString(Constants.PRODUCT_SEARCH_LIMIT));
		
		if(select_catids.size() > 0){
			String ids = "";
			for(int i = 0 ; i < select_catids.size(); i ++){
				if(i == 0){
					ids = select_catids.get(i);
				}else{
					ids += "," + select_catids.get(i);
				}
			}
			parameters.put("cid", ids);
		}
		if(select_attrids.size() > 0){
			String ids = "";
			for(int i = 0 ; i < select_attrids.size(); i ++){
				if(i == 0){
					ids = select_attrids.get(i);
				}else{
					ids += "," + select_attrids.get(i);
				}
			}
			parameters.put("aid", ids);
		}
		if(select_mallids.size() > 0){
			String ids = "";
			for(int i = 0 ; i < select_mallids.size(); i ++){
				if(i == 0){
					ids = select_mallids.get(i);
				}else{
					ids += "," + select_mallids.get(i);
				}
			}
			parameters.put("mid", ids);
		}
		if(select_brandids.size() > 0){
			String ids = "";
			for(int i = 0 ; i < select_brandids.size(); i ++){
				if(i == 0){
					ids = select_brandids.get(i);
				}else{
					ids += "," + select_brandids.get(i);
				}
			}
			parameters.put("bid", ids);
		}
		
		boolean isPriceScopeSelected = false;
		String price_scope = "";
		if(fromPriceView.getText() != null && !CommonUtils.isEmpty(fromPriceView.getText().toString())){
			price_scope = fromPriceView.getText().toString();
			isPriceScopeSelected = true;
		}
		price_scope += "_";
		if(toPriceView.getText() != null && !CommonUtils.isEmpty(toPriceView.getText().toString())){
			price_scope += toPriceView.getText().toString();
			isPriceScopeSelected = true;
		}
		if(isPriceScopeSelected){
			parameters.put("pr", price_scope);
		}
		
		httpRequester.searchGoods(parameters);
	}
	
	public void back(View view){
		if(isCategorySearch){// 返回分类搜索
			this.finish();
			overridePendingTransition(R.anim.push_right_in, R.anim.push_right_out);
		}else{// 返回首页
			Intent intent = new Intent(ProductMainActivity.this, IndexActivity.class);
			startActivity(intent);
			this.finish();
			overridePendingTransition(R.anim.push_right_in, R.anim.push_right_out);
		}
	}
	
	public void backToHome(View view){
		Intent intent = new Intent(ProductMainActivity.this, IndexActivity.class);
		startActivity(intent);
		this.finish();
		overridePendingTransition(R.anim.push_right_in, R.anim.push_right_out);
	}
	
	public void reload(View view){
		if(!isNeedReload){
			return;
		}
		if(NetworkUtils.isNetworkConnected(this)){
			isNeedReload = false;
			tv_product_loadmore_reload.setVisibility(View.GONE);
			ll_is_loading.setVisibility(View.VISIBLE);
			rl_product_count.setVisibility(View.VISIBLE);
			searchGoods(this.clearRecords);
		}else{
			Toast.makeText(
					ProductMainActivity.this,
					ProductMainActivity.this
							.getString(R.string.network_unavailable_message),
					Toast.LENGTH_LONG).show();
		}
	}
	
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		//如果按下的是返回键，并且没有重复
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			if(isCategorySearch){// 返回分类搜索
				this.finish();
				overridePendingTransition(R.anim.push_right_in, R.anim.push_right_out);
			}else{// 返回首页
				Intent intent = new Intent(ProductMainActivity.this, IndexActivity.class);
				startActivity(intent);
				this.finish();
				overridePendingTransition(R.anim.push_right_in, R.anim.push_right_out);
			}
			return false;
		}
		return false;
	}
	
	private BroadcastReceiver mNetworkStateReceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			if (!NetworkUtils.isNetworkConnected(context)) {
				Toast.makeText(
						ProductMainActivity.this,
						ProductMainActivity.this
								.getString(R.string.network_disconnect),
						Toast.LENGTH_LONG).show();
			}
		}

	};
	
	@Override
	protected void onDestroy() {
		unregisterReceiver(mNetworkStateReceiver);
		httpRequester.close();
		productListAdapter.close();
		super.onDestroy();
	}

}
